package com.software.loginregister.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.software.loginregister.R;
import com.software.loginregister.activity.MyWorksDraftActivity;
import com.software.loginregister.entity.vo.CookingStepVO;
import com.software.loginregister.entity.vo.IngredientDTO;
import com.software.loginregister.entity.vo.MyWorkDetailVO;

import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.text.Layout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;

public class MyWorksAdapter extends RecyclerView.Adapter<MyWorksAdapter.WorksViewHolder> {
    private List<MyWorkDetailVO> worksList = new ArrayList<>();

    public void setWorksList(List<MyWorkDetailVO> worksList) {
        this.worksList = worksList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public WorksViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_my_work, parent, false);
        return new WorksViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull WorksViewHolder holder, int position) {
        MyWorkDetailVO work = worksList.get(position);
        
        // 设置菜品名称
        holder.recipeTitleTextView.setText(work.getTitle());
        
        // 设置描述信息
        holder.cookingTextView.setText(work.getContentSummary());
        // 处理简介文本
        String description = work.getContentSummary();
        if (description != null) {
            // 设置简介，并添加展开/收起功能
            holder.cookingTextView.post(() -> {
                Layout layout = holder.cookingTextView.getLayout();
                if (layout != null) {
                    int lineCount = layout.getLineCount();
                    if (lineCount > 3) {
                        // 获取第三行最后一个字符的位置
                        int endOfThirdLine = layout.getLineEnd(2);
                        String truncatedText = description.substring(0, endOfThirdLine - 3) + "...";

                        // 创建可点击的文本
                        SpannableString spannableString = new SpannableString(truncatedText + " 展开");
                        ClickableSpan clickableSpan = new ClickableSpan() {
                            @Override
                            public void onClick(@NonNull View view) {
                                // 点击展开显示完整文本
                                holder.cookingTextView.setMaxLines(Integer.MAX_VALUE);
                                holder.cookingTextView.setText(description + " 收起");
                                // 重新设置点击事件
                                setCollapseClickable(holder.cookingTextView, description);
                            }

                            @Override
                            public void updateDrawState(@NonNull TextPaint ds) {
                                super.updateDrawState(ds);
                                ds.setColor(Color.parseColor("#FFD700")); // 设置"展开"文字颜色
                                ds.setUnderlineText(false);
                            }
                        };

                        spannableString.setSpan(clickableSpan,
                                truncatedText.length(),
                                spannableString.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                        holder.cookingTextView.setText(spannableString);
                        holder.cookingTextView.setMovementMethod(LinkMovementMethod.getInstance());
                    } else {
                        holder.cookingTextView.setText(description);
                    }
                }
            });
        }
        
        // 加载图片
        Glide.with(holder.itemView.getContext())
                .load(work.getImageUrl())
                .placeholder(R.drawable.default_image)
                .error(R.drawable.ic_add_photo)
                .into(holder.recipeImageView);

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            Context context = holder.itemView.getContext();
            Intent intent = new Intent(context, MyWorksDraftActivity.class);
            
            // 传递数据
            intent.putExtra("workId", work.getWorkId());
            intent.putExtra("title", work.getTitle());
            intent.putExtra("content", work.getContentSummary());
            intent.putExtra("imageUrl", work.getImageUrl());
            intent.putExtra("userId", work.getUserId());
            intent.putExtra("nickname", work.getNickname());
            intent.putExtra("avatarUrl", work.getAvatarUrl());
            intent.putExtra("likeCount", work.getLikeCount());
            intent.putExtra("commentCount", work.getCommentCount());
            
            // 处理食材列表
            StringBuilder ingredients = new StringBuilder();
            if (work.getIngredients() != null) {
                for (IngredientDTO ingredient : work.getIngredients()) {
                    ingredients.append(ingredient.getIngredientName())
                              .append(": ")
                              .append(ingredient.getAmount())
                              .append("\n");
                }
            }
            intent.putExtra("ingredients", ingredients.toString());
            
            // 处理烹饪步骤
            StringBuilder steps = new StringBuilder();
            if (work.getCookingSteps() != null) {
                for (CookingStepVO step : work.getCookingSteps()) {
                    steps.append("步骤").append(step.getStepNumber())
                         .append(": ").append(step.getDescription())
                         .append("\n");
                }
            }
            intent.putExtra("steps", steps.toString());
            
            context.startActivity(intent);
        });
    }
    private void setCollapseClickable(TextView textView, String fullText) {
        SpannableString spannableString = new SpannableString(fullText + " 收起");
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View view) {
                // 点击收起显示截断文本
                textView.setMaxLines(3);
                textView.setText(fullText);
                // 重新应用展开逻辑
                textView.post(() -> {
                    Layout layout = textView.getLayout();
                    if (layout != null && layout.getLineCount() > 3) {
                        int endOfThirdLine = layout.getLineEnd(2);
                        String truncatedText = fullText.substring(0, endOfThirdLine - 3) + "...";
                        SpannableString expandableText = new SpannableString(truncatedText + " 展开");
                        setExpandClickable(textView, fullText, expandableText);
                        textView.setText(expandableText);
                    }
                });
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#FFD700")); // 设置"收起"文字颜色
                ds.setUnderlineText(false);
            }
        };

        spannableString.setSpan(clickableSpan,
                spannableString.length() - 2,
                spannableString.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        textView.setText(spannableString);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
    }

    private void setExpandClickable(TextView textView, String fullText, SpannableString spannableString) {
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View view) {
                // 点击展开显示完整文本
                textView.setMaxLines(Integer.MAX_VALUE);
                textView.setText(fullText + " 收起");
                // 重新设置收起的点击事件
                setCollapseClickable(textView, fullText);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#FFD700")); // 设置"展开"文字颜色
                ds.setUnderlineText(false);
            }
        };

        spannableString.setSpan(clickableSpan,
                spannableString.length() - 2,
                spannableString.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        textView.setText(spannableString);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Override
    public int getItemCount() {
        return worksList.size();
    }

    static class WorksViewHolder extends RecyclerView.ViewHolder {
        ImageView recipeImageView;
        TextView recipeTitleTextView;
        TextView cookingTextView;

        public WorksViewHolder(@NonNull View itemView) {
            super(itemView);
            recipeImageView = itemView.findViewById(R.id.recipeImageView);
            recipeTitleTextView = itemView.findViewById(R.id.recipeTitleTextView);
            cookingTextView = itemView.findViewById(R.id.tv_work_description);
        }
    }
}